#include <iostream>

#include "database/scoped_connection.h"
#include "database/simple_db_pool.h"

using namespace std;
using namespace base;

void * ThreadFun(void * data) {
  SimpleConnectionPool * poolptr = (SimpleConnectionPool *)data;
  for (int i = 0; i < 10000; ++i) {
    mysqlpp::ScopedConnection cp(*poolptr);
    if (!cp) {
      cerr << "Failed to get a connection from the pool!" << endl;
      break;
    }
    // Pull a copy of the sample stock table and print a dot for
    // each row in the result set.
    mysqlpp::Query query(cp->query("select * from articles WHERE id < 100"));
    mysqlpp::StoreQueryResult res = query.store();
    // cout << "We have rows " << res.num_rows() << endl;
  }

  mysqlpp::Connection::thread_end();
  return NULL;
}

int main() {
  SimpleConnectionPool * poolptr = new SimpleConnectionPool("xingtan", "127.0.0.1:3306", "root", "");
  try {
    mysqlpp::ScopedConnection cp(*poolptr);
    if (!cp->thread_aware()) {
      cerr << "MySQL++ wasn't built with thread awareness! can't run without it." << endl;
      return 1;
    }
  } catch (mysqlpp::Exception& e) {
    cerr << "Failed to set up initial pooled connection: " <<
        e.what() << endl;
    return 1;
  }

  const int kThreadCount = 20;
  pthread_t ts[kThreadCount];

  for (int i = 0; i < kThreadCount; ++i) {
    pthread_create(&ts[i], NULL, ThreadFun, poolptr);
  }

  for (int i = 0; i < kThreadCount; ++i) {
    pthread_join(ts[i], NULL);
  }

  // Shut it all down...
  delete poolptr;
  return 0;
}

